package com.pencilisland.pay.core.service.impl;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pencilisland.pay.api.config.AppConfig;
import com.pencilisland.pay.api.util.G;
import com.pencilisland.pay.core.service.WxappService;

@Component
public class WxappServiceImpl implements WxappService {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	AppConfig appConfig;
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	ObjectMapper objectMapper;
	/**
	 * 当前使用凭证
	 */
	private static String accessToken = null;
	/**
	 * 最新更新时间戳
	 */
	private static Long updateTimeStamp = 0L;
	/**
	 * 凭证有效期
	 */
	private static Long expiresIn = 7200 * 1000L;

	@Override
	public String getAccessToken() {

		if (!StringUtils.isEmpty(accessToken)) {
			synchronized (this) {
				// 如果已经失效而且没有更新
				if ((System.currentTimeMillis() - updateTimeStamp - expiresIn) >= 0) {
					logger.info("过期刷新凭证");
					refreshAccessToken();
				}
			}
		} else {
			// 第一次获取凭证，此处同步调用
			logger.info("第一次刷新凭证");
			refreshAccessToken();
		}

		return accessToken;
	}

	/**
	 * 刷新凭证
	 */
	@SuppressWarnings("rawtypes")
	public void refreshAccessToken() {

		StringBuilder urlBuilder = new StringBuilder();
		urlBuilder.append("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=")
				.append(appConfig.getWxappAppId()).append("&secret=").append(appConfig.getWxappAppSecret());
		
		
		String result = restTemplate.getForObject(urlBuilder.toString(), String.class);
		
		logger.info("刷新凭证返回结果【{}】",result);
		if(!StringUtils.isEmpty(result)){
			Map resultMap = null;
			try {
				resultMap = objectMapper.readValue(result, Map.class);
			} catch (Exception e) {
				e.printStackTrace();
			} 
			if(resultMap!=null&& resultMap.containsKey("access_token")){
				accessToken = G.str(resultMap.get("access_token"));
				expiresIn = G.l(resultMap.get("expires_in")) * 1000;
				updateTimeStamp = System.currentTimeMillis();

				// 设置定时刷新accessToken
				Timer timer = new Timer();
				timer.schedule(new refreshAccessTokenTimeTask(), expiresIn - 30000);
			}
		}

	}

	public class refreshAccessTokenTimeTask extends TimerTask {

		@Override
		public void run() {
			logger.info("定时刷新accessToken");
			refreshAccessToken();
		}

	}
	
	@Override
	public void sendTemplate(Object body){
		StringBuilder urlBuilder = new StringBuilder();
		urlBuilder.append("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=").append(getAccessToken());
		
		String result = null;
		try {
			result = restTemplate.postForObject(urlBuilder.toString(), objectMapper.writeValueAsString(body), String.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		logger.info("发送模板消息返回："+result);
	}
}
